package com.cy.store.Service.Impl;

import com.cy.store.Entity.Address;
import com.cy.store.Mapper.AddressMapper;
import com.cy.store.Mapper.UserMapper;
import com.cy.store.Service.Ex.*;
import com.cy.store.Service.IAddressService;
import com.cy.store.Service.IDistrictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 新增收货地址的实现
 */
@Service
public class AddressServiceImpl implements IAddressService {
    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private UserMapper userMapper;

    //在添加用户的收货地址业务层依赖于省市区业务层
    @Autowired
    private IDistrictService districtService;

    /**
     * 最大收货地址数量
     */

    @Value("${user.address.max-count}")
    private Integer addressMaxCount;

    @Override
    public Integer addNewAddress(Integer uid, String username, Address address) throws AddressCountLimitException, InsertException {
        Integer count = addressMapper.countByUid(uid);
        if(count >= addressMaxCount){
            throw new AddressCountLimitException("用户的收货地址不能超过20个");
        }


        //对address对象中的数据进行补全：省市区
        String provinceName= districtService.getDistrictNameByCode(address.getProvinceCode());
        String cityNmame = districtService.getDistrictNameByCode(address.getCityCode());
        String areaName = districtService.getDistrictNameByCode(address.getAreaCode());
        address.setAreaName(areaName);
        address.setCityName(cityNmame);
        address.setProvinceName(provinceName);


        //如果收货地址数量为0则设为默认地址
        address.setUid(uid);
        Integer isdefault =count==0? 1:0;
        address.setIsDefault(isdefault);

        //设置创建人（时间），修改人（时间）
        address.setCreatedTime(new Date());
        address.setCreatedUser(username);
        address.setModifiedTime(new Date());
        address.setModifiedUser(username);

        //插入收货地址的方法
        Integer rows=addressMapper.insert(address);

        if(rows != 1){
            throw new InsertException("新增收货地址过程中出现未知的异常");
        }
        return rows;
    }

    @Override
    public List<Address> getByUid(Integer uid) {
        List<Address> list=addressMapper.findByUid(uid);
        for(Address address:list){
//            address.setUid(null);
//            address.setAid(null);
//            address.setZip(null);
            address.setCreatedTime(null);
            address.setModifiedTime(null);
            address.setModifiedUser(null);
            address.setCreatedUser(null);
            address.setModifiedUser(null);
//            address.setProvinceName(null);
            address.setProvinceCode(null);
//            address.setCityName(null);
            address.setCityCode(null);
//            address.setAreaName(null);
            address.setAreaCode(null);
        }
        return list;
    }

    @Override
    public void setDefault(Integer aid, Integer uid, String username) throws AddressNotFoundException, AccessDeniedException, UpdateException {
        //1.检测是否有该条收货地址数据
        Address result = addressMapper.findByAid(aid);
        if (result == null) {
            throw new AddressNotFoundException("收货地址不存在");
        }

        //2.检测当前获取到的收货地址数据的归属
        if (!result.getUid().equals(uid)) {
            throw new AccessDeniedException("非法数据访问");
        }

        //3.先将所有的收货地址设置为非默认
        Integer rows = addressMapper.updateNonDefault(uid);
        if (rows < 1) {
            throw new UpdateException("更新数据时产生未知的异常");
        }

        //4.将用户选中的地址设置为默认收货地址
        rows = addressMapper.updateDefaultByAid(aid, username, new Date());
        if (rows != 1) {
            throw new UpdateException("更新数据时产生未知的异常");
        }
    }

    @Override
    public void delete(Integer aid, Integer uid, String username) throws AddressNotFoundException, AccessDeniedException, DeleteException, UpdateException {
        Address result = addressMapper.findByAid(aid);
        //1.
        if (result == null) {
            throw new AddressNotFoundException("收货地址数据不存在");
        }
        //2.
        if (!result.getUid().equals(uid)) {
            throw new AccessDeniedException("非法数据访问");
        }
        //3.
        Integer rows = addressMapper.deleteByAid(aid);
        if (rows != 1) {
            throw new DeleteException("删除数据时产生未知的异常");
        }
        //4.如果删除的是非默认地址则不需要再做后面的任何操作,终止程序
        if (result.getIsDefault() == 0) {
            return;
        }
        //5.
        Integer count = addressMapper.countByUid(uid);
        if (count == 0) {
            return;
        }
        //6.
        Address address = addressMapper.findNewestAddressByModifiedTime(uid);
        //7.
        rows = addressMapper.updateDefaultByAid(address.getAid(), userMapper.findByUid(uid).getUsername(), new Date());
        if (rows != 1) {
            throw new UpdateException("更新数据时产生未知的异常");
        }


    }

    @Override
    public Address getByAid(Integer aid, Integer uid) throws AddressNotFoundException, AccessDeniedException {

        Address address = addressMapper.findByAid(aid);

        if (address == null) {
            throw new AddressNotFoundException("收货地址数据不存在的异常");
        }
        if (!address.getUid().equals(uid)) {
            throw new AccessDeniedException("非法访问");
        }
        address.setProvinceCode(null);
        address.setCityCode(null);
        address.setAreaCode(null);
        address.setCreatedUser(null);
        address.setCreatedTime(null);
        address.setModifiedUser(null);
        address.setModifiedTime(null);
        return address;
    }

}
